--[[
Gemböbble
Copyright (c) 2010-2011 Carl Ådahl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
Map = {}
local maxWidth = 8       -- maximum width of map in cells
local maxHeight = 13     -- maximum height of map in cells

function Map.new()

	local s = Actor.new("map")
	s.won = false
	local cells = {}
	local debugPoints = {} 
	local mapNumber = 0 -- none yet
	local lookups = {}

    -- Initialize the cell grid.
    for i = 0,maxWidth*maxHeight-1 do
        cells[i] = {}
    end
    
    -- Initialize color lookups.
	for i=1,Ball.colorCount do
		lookups[""..(i-1)] = i
	end

	function s.nextMap()
        s.loadMap(s.lines)
	end

    local function getCellCountX(j)
       	return maxWidth-math.mod(j,2)
    end

    local function getCellCountY()
        return maxHeight
    end

    local function getX(i, j)
        return (i + math.mod(j,2) * 0.5 + 0.5) * cfg.columnWidth
    end

    local function getY(i, j)
        return (j + 0.5) * cfg.rowHeight
    end

    local function getCell(i, j)
        if i >= 0 and j >= 0 and j < getCellCountY() and i < getCellCountX(j) then
	        return cells[i + j * maxWidth]
        end
    end

	local function forEachNeighbor(i,j,func)
	    func(i-1, j)
	    func(i+1, j)
	    if math.mod(j,2) == 1 then
	        func(i, j-1)
	        func(i+1, j-1)
	        func(i, j+1)
	        func(i+1, j+1)
	    else
	        func(i-1, j-1)
	        func(i, j-1)
	        func(i-1, j+1)
	        func(i, j+1)
	    end
	end

	function s.handleMatches(firsti, firstj)
        local matches = {}
        local matchCount = 0
		local firstc = getCell(firsti, firstj)

		local function match(i, j)
		    local c = getCell(i,j)
		    if c and c.ball and not matches[c.ball] and c.ball.color == firstc.ball.color then
		        matches[c.ball] = { i, j }
				matchCount = matchCount + 1
				forEachNeighbor(i, j, match)
		    end
		end
        
        match(firsti, firstj)

		if matchCount >= 3 then
			return matches
		end
    end

    function s.setBall(i, j, ball)
        local c = getCell(i,j)
        if c then
	        c.ball = ball
	    end
    end

	function s.getColors()
		local colors = {}
		
		local remainingColors = {}
		for _,c in pairs(cells) do
		    if c and c.ball then
				remainingColors[c.ball.color] = true
		    end
		end
				
		for color,_ in pairs(remainingColors) do table.insert(colors, color) end
        return colors
    end

    local function markAttached(i, j)
        local c = getCell(i,j)
        if c and c.ball and not c.attached then
		    c.attached = true
--		    remainingColors[c.ball.color] = true
			forEachNeighbor(i, j, markAttached)
        end
    end

	function s.findFreeCell(x, y)
		debugPoints = {}
		local fi,fj,fx,fy,fd = -1,-1,-1,-1,math.huge
		
		local function testCell(i,j)
            local c = getCell(i,j)
        --   	debugPoints[#debugPoints+1] = { cx, cy }
            if c and not c.ball then
		    	local cx, cy = getX(i,j), getY(i,j)
                local d = (cx-x)^2 + (cy-y)^2
                if d < fd then
                    fi, fj, fx, fy, fd = i, j, cx, cy, d
                end
            end
		end
		
	    local j = math.floor(y/cfg.rowHeight) -- rounding built in!
		local odd = math.mod(j,2)
	    local i = math.floor(x/cfg.columnWidth - odd * 0.5) -- rounding built in!

        -- 	debugPoints[#debugPoints+1] = { getX(i,j)+5, getY(i,j)+5 }
		testCell(i,j)
		forEachNeighbor(i, j, testCell)
		
		return fi, fj, fx, fy 
    end

	function s.nextMap(lines)

		local cachedLines = {}	
	
		local ballCount = 0
		local j = 0
		repeat
			local line = lines()
			table.insert(cachedLines, line)
			line = line:gsub(" ", "")
	
			for i = 1, line:len() do
				-- Look up the color index of this ball.
	            local color = lookups[line:sub(i,i)]
	            if color then
	            	-- Spawn a ball with this color.
	                local ball = world.spawn(Ball.new(getX(i-1,j), getY(i-1,j), color))

					-- Tell the ball to wait off-screen one screenful up.
	                ball.enterState("standby", cfg.height)
	                getCell(i-1,j).ball = ball
	                ballCount = ballCount + 1
	            end
			end

			j = j + 1			
		until line:len() == 0

		mapNumber = mapNumber + 1

		s.currentMap = cachedLines
		
		print("Map: Loaded level " .. mapNumber .. " (" .. ballCount .. " balls).")
	end

	function s.draw()
		love.graphics.setPointSize(5)
		for _,v in pairs(debugPoints) do
			love.graphics.point(v[1], v[2])
		end
	end

	function s.states.loading(loadNext)
		-- Load the next map
		if loadNext then
			s.nextMap(s.lines)
		else
			mapNumber = mapNumber - 1
			local i = 0
			s.nextMap(function() 
				i = i + 1
				return s.currentMap[i] 
			end )
		end
		
		-- Tell the bg to scroll in the level heading and the level itself.
		background.enterState("loading", mapNumber)

		-- Wait for that to complete. The balls will also sync with the background.
		s.waitUntil(background, "playing")

		-- All done, now spawn the camera.
		cannon = world.spawn(Cannon.new(love.graphics.getWidth()/2, love.graphics.getHeight()))

		-- And start playing.
		s.enterState("playing")
	end

	function s.updateBalls()
		for _,c in pairs(cells) do
			c.attached = false
		end
	
		for i = 0, getCellCountX(0)-1 do
	        markAttached(i, 0)
	    end

	    for _,c in pairs(cells) do
	        if c.ball and not c.attached then
				c.ball.enterState("dying")
		        c.ball = nil
		    end
	    end
	end

	function s.states.playing()

		while s.update() do
			s.updateBalls()		
		    
		    local ballsOnMap = false
		    for j = 0, getCellCountY()-1 do
		        for i = 0, getCellCountX(j)-1 do
		            local c = getCell(i,j)
					if c.ball then
						ballsOnMap = true
				--		print(i .. ", " .. j .. " has a ball")
						break
					end
				end
			end

		    local lose = false
			for j = 12, getCellCountY()-1 do
				for i = 0, getCellCountX(j)-1 do
		            local c = getCell(i,j)
					if c.ball then
						s.enterState("lost")
						s.wait()
					end
				end
			end

			if ballsOnMap then
				if cannon.state == "ready" then
					cannon.enterState("loading") 
				end
			else
				background.enterState("standby")
				world.remove(cannon)
				cannon = nil
				s.enterState("loading", true)        	
			end
		end
	end

	function s.states.lost()
		background.enterState("standby")
		world.remove(cannon)
		cannon = nil
		
		for _,c in pairs(cells) do
			if c.ball then
				c.ball.enterState("dying")
				c.ball = nil
			end
		end
		
		s.waitFor(60)
		background.enterState("lost")
		s.waitUntil(background, "lost")
		s.waitUntil(background, "standby")
		s.enterState("loading", false)
		s.wait()
	end

	function s.getWithinRadius(actor, filterType, distance)
		local matches
		
        for j = 0, getCellCountY()-1 do
            for i = 0, getCellCountX(j)-1 do
                local c = getCell(i,j)
				if c.ball and c.ball ~= actor then
					local dx = actor.getX() - getX(i,j)
					local dy = actor.getY() - getY(i,j)
					local od2 = dx*dx + dy*dy
					
					if od2 <= distance^2 then
						matches = matches or {}
						table.insert(matches, c.ball)
					end			
				end
			end
		end
		
		return matches
	end

	function s.states.credits()
		background.enterState("credits")
		s.waitUntil(background, "credits")
		s.waitUntil(background, "standby")
		s.waitKey()
		s.enterState("loading", true)
	end

	s.setUpdatePriority(-2)

    -- Load the map itself.
	s.lines = love.filesystem.lines("levels.txt")
    s.enterState("credits")
    
	return s
end

